package com.school.demo.controller;

import com.school.demo.model.auto.User;
import com.school.demo.service.IUserService;
import com.school.demo.util.Restful;
import com.school.demo.util.Status;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: demo
 * @description: Android端登录api接口
 * @author: Charlotte
 * @create: 2021-03-13 17:57
 **/

@Api(tags = "用户登录")
@RestController
@RequestMapping("/user")
public class LoginController {


    @Autowired
    IUserService userService;

    @ApiOperation(value = "用户登录", notes = "", tags = {})
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public @ResponseBody
    Restful login(String userName,String password) throws Exception {

        //获取Subject对象
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userName,password);

        //设置记住用户
        token.setRememberMe(false);

        //判断登录状态并处理异常
        try {
            subject.login(token);
            return new Restful(Status.SUCCESS);
        }catch (UnknownAccountException e){
            //用户名不存在
            return new Restful(Status.LOGIN_ERROR);
        }catch (IncorrectCredentialsException e){
            //密码错误
            return new Restful(Status.LOGIN_ERROR);
        }

//        Map<String,Object> map = new HashMap<>();
//        map = userService.login(map);
//        return map;

    }


    @GetMapping("/hello")
    public String hello(){
        return "dsaf ";
    }


    @ApiOperation(value = "退出登录", notes = "", tags = {})
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public @ResponseBody
    Restful logout(@RequestBody String json) throws Exception {

        Subject user = SecurityUtils.getSubject();
        user.logout();
        return new Restful(Status.SUCCESS);

    }


    @ApiOperation(value = "注册", notes = "", tags = {})
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> register(@RequestBody User user) throws Exception {

        Map<String,Object> map = new HashMap<>();
        map = userService.register(user);
        return map;

    }

}
